<template>
    <div class="couponlist-wrap" style="flex:1;">
        
        <wxc-minibar title="使用优惠券">
            <div class="header-font-title" slot="right" @click="save">
                <text class="header-font-pr">完成</text>
            </div>
        </wxc-minibar>
        <scroller class="scroller"  style="position: fixed;top:90px;bottom:80px;left: 0px;right: 0px;">
            <refresh @refresh="onrefresh" class="refresh" :display="refreshing ? 'show' : 'hide'">
                <rotate></rotate>
                <!-- <text style="font-size:28px;">数据加载中。。。</text>
                <loading-indicator class="indicator"></loading-indicator> -->
            </refresh>

            <div v-for="(item,key) in dataList" v-if="dataList && dataList.length > 0 && item.bothUse === 0" class="cell" :key="key" >
                <div class="coupon-itemWrap" @click="changeRadio(item)">
                    <div class="counpon-item">
                         <div class="item-left" >
                                <image  src="https://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/couponBg.png" class="item-bg"></image>
                                <div class="itemn-topTxt">
                                      <text class="lefticon" >￥</text>
                                     <text class="left-txt">{{item.amount}}</text>
                                </div>
                                <div class="itemn-botTxt">
                                    <text class="common-txt1">{{item.availableCondition}}</text>
                                </div>

                            </div>
                          <div class="item-middle">
                            <text class="item-txtTop">{{formatName(item.couponName)}}</text>
                            <text class="common-txt item-txtBot">{{item.endTime | filtertime}}有效</text>
                             <div class="itemn-flagWrap">
                                    <div class="itemn-man itemn-man1"  v-if="item.couponType">
                                        <text class="itemn-txt itemn-txt1" v-if="item.couponType==2" >满减券</text>
                                        <text class="itemn-txt itemn-txt1" v-if="item.couponType==1" >抵扣券</text>
                                    </div>
                                    <div class="itemn-man itemn-man2" v-if="item.newUser">
                                        <text class="itemn-txt itemn-txt2" >新用户专享</text>
                                    </div>
                                    
                                </div>
                        </div>
                        <div class="item-right" >
                            <div  class="whiteicon" v-if="radioValue != item.relationNo"></div>
                            <image v-if="radioValue == item.relationNo"  style="width:40px;height:40px;" src="http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/checked.png"></image>
                        </div>
                   
                        </div>
                </div>
            </div>

            <div v-for="(item,key) in dataList" v-if="dataList && dataList.length>0 && item.bothUse === 1" class="cell" :key="key">
                <div class="coupon-itemWrap" @click="changeSelect(item)">
                    <div class="counpon-item">
                          <div class="item-left" >
                                <image  src="https://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/couponBg.png" class="item-bg"></image>
                                <div class="itemn-topTxt">
                                      <text class="lefticon" >￥</text>
                                     <text class="left-txt">{{item.amount}}</text>
                                </div>
                                <div class="itemn-botTxt">
                                    <text class="common-txt1">{{item.availableCondition}}</text>
                                </div>

                            </div>
                        <div class="item-middle">
                            <text class="item-txtTop">{{formatName(item.couponName)}}</text>
                            <text class="common-txt item-txtBot">{{item.endTime | filtertime}}有效</text>
                             <div class="itemn-flagWrap">
                                    <div class="itemn-man itemn-man1"  v-if="item.couponType">
                                        <text class="itemn-txt itemn-txt1" v-if="item.couponType==2" >满减券</text>
                                        <text class="itemn-txt itemn-txt1" v-if="item.couponType==1" >抵扣券</text>
                                    </div>
                                    <div class="itemn-man itemn-man2" v-if="item.newUser">
                                        <text class="itemn-txt itemn-txt2" >新用户专享</text>
                                    </div>
                                     <div class="itemn-man itemn-man1">
                                        <text class="itemn-txt itemn-txt1">可叠加</text>
                                    </div>
                                </div>
                        </div>
                        <div class="item-right" >
                            <div  class="whiteicon" v-if="selectList.indexOf(item.relationNo) === -1"></div>
                            <image v-if="selectList.indexOf(item.relationNo) > -1"  style="width:40px;height:40px;" src="http://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/checked.png"></image>
                        </div>
                     
                        </div>
                </div>
            </div>

            <div v-if="norecord" class="norecord">
                <image style="width:298.5px;height:298.5px;" src="https://zhongcai-test.oss-cn-beijing.aliyuncs.com/hch5/nocoupon.png"></image>
                <text style="margin-top:71.7px;font-size: 40px;color: #9E8383;">暂无优惠券</text>
            </div>
            <loading class="loading" @loading="onloading" :display="loadinging ? 'show' : 'hide'" v-if="!notLoding">
                <rotate></rotate>
                <!-- <loading-indicator class="indicator"></loading-indicator> -->
            </loading>
        </scroller>
         <loading-big v-if="loadingshow"></loading-big>
        <!-- <wxc-loadingsp :show="loadingshow" type="custom" :need-mask="true" loading-text="加载中..." m-url="http://img.alicdn.com/tfs/TB1Ep_9NVXXXXb8XVXXXXXXXXXX-74-74.gif" m-width="200" m-height="200" m-backgroundcolor="#212021" m-textcolor="#ffffff"></wxc-loadingsp> -->
    </div>
</template>
<script>
import { WxcTabPage, WxcPanItem,  Utils,  BindEnv } from "weex-ui";
import WxcMinibar from "@/components/modules/wxc-minibar/index.js"
import Config from "@/tab-bar/topconfig";
import WxcLoadingsp from "@/components/modules/loading";
import { serialize,  getBaseUrl, jsonAnalysis } from "@/utils/index.js";
import { postResponsesToken } from "@/api.js";
import rotate from "@/components/modules/rotate";
import loadingBig from "@/components/modules/loading-big";
const storage = weex.requireModule("storage");
const modal = weex.requireModule("modal");
const navigator = weex.requireModule("navigator");
let discountCoupon = new BroadcastChannel('discountCoupon')

export default {
    components:{
        WxcTabPage,
        WxcMinibar,
        WxcLoadingsp,
        rotate,
        loadingBig
    },
    data(){
        return{
            loadingshow: false,
            refreshing: false,
            loadinging: false,
            notLoding:false,
            norecord: false,
            pagesize: 10, // 一页显示多少条
            pageindex: 1, //当前页
            baseURL: "",
            tabFlag:0,//用来标识导航
            checkflag:false,
            dataList:[], 
            radioValue:'', //单选优惠券
            selectList:[] //多选优惠券
            
        }
    },

    mounted(){
        this.getresposnedata(true);
        // 获取路径
        this.baseURL = getBaseUrl(weex.config.bundleUrl, true);
    },

    filters:{
        filtertime(time) {
            let date = new Date(time)
            let formatNum = (num) => { return num < 10 ? "0" + num : num.toString() }

            return `${date.getFullYear()}-${formatNum(date.getMonth() + 1)}-${formatNum(date.getDate())} ${formatNum(date.getHours())}:${formatNum(date.getMinutes())}`
        }
    },
    methods:{
          formatName(name){
            let obj=this.strlen(name);
            return obj.len>16 ? name.slice(0,obj.count)+'...':name; 
        },
         strlen(str){
             let obj={
                 len:0,
                 count:0,
             }
            var len = 0;
            for (var i=0; i<str.length; i++) { 
                var c = str.charCodeAt(i); 
                //单字节加1 
                    if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f))    { 
                    obj.len++; 
                    } 
                    else { 
                    obj.len+=2; 
                    } 
                    if(obj.len<=16){
                        obj.count++;
                    }
            } 
            return obj;
        },
        // 保存选中优惠券
        save() {
            let curIarr = this.radioValue != '' ?  Array.of(this.radioValue) : this.selectList
            let iarr = this.dataList.filter(v=> curIarr.indexOf(v.relationNo) > -1 )
            let baseCoupon = 0

            iarr.forEach(v=> baseCoupon += +v.amount )
   
            this.cacheMark('discountCoupon', {'money': baseCoupon, 'id': curIarr.join(',')}).then((value)=>{
                discountCoupon.postMessage('post')
                navigator.pop()
            })
            
        },

        //缓存数据
		cacheMark(name, values) {
			return new Promise((resolve, rejects) => {
				storage.setItem(name, JSON.stringify(values), event => {
					if (event.result === "success" && event.data != '') {
						resolve(true);
					} else {
						rejects("缓存数据失败");
					}
				})
			})
        },
        
        // 单选优惠券
        changeRadio(item) {
            this.radioValue =  this.radioValue === item.relationNo ? '' :  item.relationNo
            this.selectList = []
        },

        // 多选优惠券
        changeSelect(item) {
            let index = this.selectList.indexOf(item.relationNo)
            index > -1 ? this.selectList.splice(index, 1) : this.selectList.push(item.relationNo)
            this.selectList.length > 0 && ( this.radioValue = '' )
        },

        //点击使用到首页
        goHome(){

              navigator.push({
                url: this.baseURL + "index.js",
                animated: "true"
            });
        },
        
        //请求优惠券列表页数据
        async getresposnedata(state) {
            this.loadingshow = true
            this.refreshing = true
            

            try {
                
                let getJson = jsonAnalysis(weex.config.bundleUrl.split('?')[1])
                
                let getParam = getJson['id'].split(',')
                
                let param = {
                    page:{
                        size: this.pagesize,//分页大小，一页展示多少条
                        current: this.pageindex//当前页面
                    },
                    castMoney: getJson['castMoney'],
                    lotteryCode: getJson['lotteryCode'],
                    type: 0//类型0：未使用，1:已使用,2:已过期
                }

                let res = await postResponsesToken('account/activity/getMyCoupon', param);//发请求

                this.loadingshow = false;

                if (res.data.records.length === 0) {
                    this.norecord = true
                } else {
                    this.norecord = false;
                }

                if (this.pageindex !== 1) this.norecord = false;

               let demoList=res.data.records;
             
               
                this.dataList= !!state ? demoList : this.dataList.concat(demoList);

                
                
                this.dataList.forEach((value, index)=>{
                    if( value.bothUse === 0 && getParam.indexOf(value.relationNo) >-1) {
                        this.radioValue = value.relationNo
                    }

                    if( value.bothUse === 1 && getParam.indexOf(value.relationNo) >-1) {
                        this.selectList.push(value.relationNo)
                    }

                    
                })

                this.refreshing = false
                this.loadinging = false
                this.notLoding = demoList.length < this.pagesize 

            } catch (e) {
                this.loadingshow = false
            }
        },
          
        onrefresh(event) {
            this.pageindex = 1
            this.getresposnedata(true);

        },
        onloading(event) {
            if( !!this.notLoding) return 
            this.loadinging = true
            this.pageindex++
            this.getresposnedata()

        },
    }
}
</script>
<style scoped>
.loading{
    width: 750px;
    display: flex;
    align-items: center;
   
}
.header-font-pr {
  font-size: 28px;
  color: #fff;
}

.scroller {
    width:750px;
    /* display: flex; */
}


.refresh {
    width: 750px;
    display: flex;
    align-items: center;
}
.norecord {
    padding-top: 158px;
    padding-left: 225.8px;
    padding-right: 225.8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.border-cell {
    background-color: #f2f3f4;
    width: 750px;
    height: 24px;
    align-items: center;
    justify-content: center;
}
.item-container {
    width: 750px;
    background-color: rgb(245, 245, 245);
}

.couponlist-wrap{
    width: 750px;
    position: relative;
    background-color: #f2f3f4;
    z-index: 2;
}
    .coupon-itemWrap{
         flex-direction: column;
         align-items: center;
    }
    .counpon-item{
          width:686px;
      
        height:184px;
        margin-top:24px;
        flex-direction: row;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
        border-bottom-left-radius: 8px;
        border-bottom-right-radius: 8px;
          overflow: hidden;
    }
     .item-left{
        width:240px;
        height:184px;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        position: relative;
        
      
    }
    .item-bg{
       position:absolute;
       left:0;
       top:0;
         width:240px;
        height:184px;
    }
    .item-middle{
        width:330px;
        height:184px;
        padding-left:24px;
        flex-direction: column;
        background-color: #fff;
    }
    .item-right{
         width:116px;
         height:184px;
        justify-content: center;
        background-color: #fff;
    }
     .lefticon{
            font-size: 40px;
            margin-top:10px;
            color:#fff;
    }
    .left-txt{
         font-size: 60px;
          color:#fff;
    }
    .item-txtTop{
        color:#333333;
        font-size:28px;
        margin-top:24px;
        font-family:PingFangSC-Medium;
         lines:1;
    }
    .common-txt{
        color:#999;
        font-size:20px;
        margin-top:10px;
    }
    .item-button{

        background-color: #E70D0D;
      width:88px;
      height:48px;
        border-top-left-radius: 32px;
        border-top-right-radius: 32px;
        border-bottom-left-radius: 32px;
        border-bottom-right-radius: 32px;
        justify-content: center;
        align-items: center;
    }
    .item-butTxt{
        color:#fff;
        font-size:24px;
    }
  
 
   .new-flag{
       width:300px;
       height:30px;
       position:absolute;
      
       right:-150px;
       top:0px;
       transform:translate(-30px,20px)  rotate(45deg);
     transform-origin: center center;
        background-color: #E70D0D;
       
   } 
    .new-flagtxt{
        color:#fff;
        font-size:14px;
        text-align: center;
        padding-top:5px;
    }
.new-flagImg{
       width:90px;
       height:78px;
}


.coupon-flag{
     width:211px;
       height:132px;
      
       position:absolute;
       right:8px;
       top:20px;
     
}
.coupon-flagImg{
     width:211px;
       height:132px;
}
.bgred{
    background-color: #E70D0D;
}
.bggray{
background-color: #999999;
}
.graytxt{
    color:#999999;
}
.redtxt{
 color:#E70D0D;

}
.whiteicon{
    width:40px;
    height:40px;
    background-color:white;
    border-radius:50px;
    border-width:1px;
    border-color:rgba(0,0,0,0.1);
}
.itemn-topTxt{
      flex-direction: row;
}
.itemn-flagWrap{
    flex-direction: row;
    margin-top:30px;
}
.itemn-man{
    padding-left:10px;
    padding-right:10px;
  
    border-style: solid;
    border-width: 1px;
   
    margin-right:10px;
    border-radius: 30px;
    height:30px;
    justify-content: center;
   
}
.itemn-txt{
    font-size:16px;
   
}
.itemn-txt1{
    color:#F99F3B;
}
.itemn-txt2{
   color:#F15B5B;
}
.itemn-man1{
    border-color:#F99F3B;
}
.itemn-man2{
    border-color:#F15B5B;
}
.common-txt1{
     color:#fff;
     font-size:20px;
     margin-top:10px;
 }
</style>